import React, {useEffect, useState} from 'react';
import axios from "axios";
import {Link} from "react-router-dom";
import {CheckOutlined,CloseOutlined} from '@ant-design/icons'
import {Button, Table} from "antd";


const Audit = () => {
    const [dataSource,setDataSource]=useState([])
    const {roleId,username,region} = JSON.parse(localStorage.getItem('token'))


    const columns = [
        {
            title: '新闻标题',
            dataIndex: 'title',
            render:(title,item)=>{
                return <Link to={`/news-manage/preview/${item.id}`}>{title}</Link>
            }
        },
        {
            title: '作者',
            dataIndex: 'author',
            render:(key)=>{
                return <div>{key}</div>
            }
        },
        {
            title: '分类',
            dataIndex: 'category',
            render:(category)=>{
                return category.title
            }
        },
        {
            title: '操作',
            render:(item)=>{
                return <div>
                    <Button type={"primary"} shape={"circle"} icon={<CheckOutlined />} onClick={()=>{handleCheck(item)}} style={
                        {marginRight:'10px'}
                    }/>
                    <Button danger shape={"circle"} icon={<CloseOutlined />} onClick={()=>{handleClose(item)}}/>
                </div>
            }
        }
    ]

    useEffect(()=>{
        axios.get(`/news?auditState=1&_expand=category`).then(
            res=>{
                const list = res.data
                setDataSource(roleId===1?list:[
                    ...list.filter(item=>item.username===username),
                    ...list.filter(item=>item.region===region && item.roleId===3)
                ])
            }
        )
    },[username,region,roleId])

    const handleCheck=(item)=>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            auditState:2,
            publishState:1
        })
    }
    const handleClose=(item)=>{
        setDataSource(dataSource.filter(data=>data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            auditState:3,
            publishState:0
        })
    }

    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{pageSize:10}} rowKey={item=>item.id}/>
        </div>
    );
};

export default Audit;